package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 目标：
 *
 * @author Ashely
 * @date 2024/6/17 16:28
 */
@RestController
@RequestMapping("/user/addressBook")
@Api(tags = "地址管理接口")
@Slf4j
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;
    @PostMapping
    @ApiOperation("新增地址接口")
    public Result add(@RequestBody AddressBook addressBook) {
        addressBookService.add(addressBook);
        return Result.success();
    }
    @GetMapping("/list")
    @ApiOperation("查看地址接口")
    public Result list() {
        AddressBook addressBook = AddressBook.builder().userId(BaseContext.getCurrentId()).build();
        return Result.success(addressBookService.list(addressBook));
    }
  @GetMapping("/{id}")
    @ApiOperation("根据id查询地址接口")
    public Result getById(@PathVariable Long id) {
      AddressBook addressBook = addressBookService.getById(id);
      return Result.success(addressBook);
    }
    @PutMapping
    @ApiOperation("修改地址接口")
    public Result update(@RequestBody AddressBook addressBook) {
        addressBookService.update(addressBook);
        return Result.success();
    }
    @DeleteMapping
    @ApiOperation("删除地址接口")
    public Result delete(Long id) {
        addressBookService.delete(id);
        return Result.success();
    }
    @PutMapping("/default")
    @ApiOperation("设置默认地址接口")
    public Result setDefault(@RequestBody AddressBook addressBook) {
        addressBookService.setDefault(addressBook);
        return Result.success();
    }
    @GetMapping("/default")
    @ApiOperation("查询默认地址接口")
    public Result getDefault() {
        AddressBook addressBook = AddressBook.builder().isDefault(1).userId(BaseContext.getCurrentId()).build();
        List<AddressBook> list = addressBookService.list(addressBook);
        if (list != null && list.size() == 1){
            return Result.success(list.get(0));
        }
        return Result.error("没有查询到默认地址");
    }
}
